from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from users.models import UserModel
from users.serializers import RegisterSerializer
from rest_framework import status
from fuguang.utils.SmsApis import send_message
from django.conf import settings
import random
from django_redis import get_redis_connection


# 测试视图，用于创建用户
class CreateUserViews(APIView):
    def get(self, request):
        # UserModel.objects.create()  表示往数据单纯得插入一条数据
        UserModel.objects.create_user(username='root', email='123@123.com', password='123', mobile="18000000000")
        # user = UserModel.objects.create(username='shanshan',email='123@123.com',password='123',mobile="18000000001")
        # user.set_password('123')
        return Response({"message": "用户创建成功"})


# 选用什么视图？？？？？
# APIView ：
# CreateApiView  :序列化器中实现业务逻辑判断
# 序列化器：序列化：orm得模型对象转成json格式得字符串，，，和反序列化将json格式得字符串转成模型对象
# 数据校验
# 保存数据
# update
class RegisterViews(CreateAPIView):
    queryset = UserModel.objects.all()
    serializer_class = RegisterSerializer


# 手机号唯一注册
class MobileViews(APIView):
    def get(self, request, mobile):
        try:
            UserModel.objects.get(mobile__exact=mobile)
            return Response({'message': '手机号已存在，请登录或修改密码！'}, status=status.HTTP_400_BAD_REQUEST)
        except UserModel.DoesNotExist:
            return Response({'message': '手机号允许注册！'}, status=status.HTTP_200_OK)


class SmsApiView(APIView):
    def get(self, request, mobile):
        # -------------------redis:短信验证码------------------
        redis = get_redis_connection('sms_code')
        res_interval = redis.ttl(f'sms_{mobile}')
        if res_interval != -2:
            return Response({'message': '验证码还在有效期内,请勿频繁发送验证码'}, status=status.HTTP_400_BAD_REQUEST)
        # -------------------redis:短信验证码------------------

        # 获取容联云配置信息
        rly = settings.RONG_LIAN_YUN
        # 获取短信模板
        tid = rly.get('reg_tid')
        sms_expire = rly.get('sms_expire')
        # 获取发送间隔
        sms_interval = rly.get('sms_interval')

        # mobile = '18201275696'
        # 生成验证码，格式化操作，不足4位，前面补0
        code = f'{random.randint(0, 9999):04d}'
        # 配置文件中秒位单位，容联云以分钟位单位
        interval = sms_interval / 60
        # 基本发送短信完成
        # 如何存储验证码
        # 生成发送短信的datas
        datas = (code, interval)
        # tid = "1"
        # mobile = '18201275696'
        # datas = ('9823', '2')
        # 调用发送验证码函数
        # res = send_message(tid, mobile, datas)
        from mycelery.sms.tasks import send_sms
        send_sms.delay(tid, mobile, datas)

        # -------------------redis:短信验证码------------------
        # redis写入验证码,     sms_18201275699
        # redis  提供了  简单事务
        # 开启管道,优化redis写入, 执行的,一次性将所有指令发送给redis
        # 开启事务
        pipe = redis.pipeline()
        pipe.multi() # 开启redis事务,保证所有命令 正确执行
        redis.setex(f'sms_{mobile}', sms_expire, code)
        # 短信发送的间隔时间
        redis.setex(f'interval_{mobile}', sms_interval, '-')
        # 提交事务,把暂存在pipeline对象中多条命令,一次性提交给redis
        pipe.execute()
        # -------------------redis:短信验证码------------------

        # if res:
        return Response({'message': '短信发送成功...'}, status=status.HTTP_200_OK)
        # else:
        #     return Response({'message': '短信发送失败...'}, status=status.HTTP_400_BAD_REQUEST)
